﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ApplicationGenerator.CommonModule
{
    public class UserManager
    {
        private static List<UserEntity> _users = new List<UserEntity>();

        public static string FilePath
        {
            get;
            set;
        }

        public static void GetUsers()
        {
            foreach (var fileLine in File.ReadAllLines(FilePath))
            {
                string[] userInfo = fileLine.Split(new[] { ":" }, StringSplitOptions.None);
                if (userInfo.Length != 3)
                {
                    continue;
                }

                UserEntity newUser = new UserEntity();
                newUser.Name = userInfo[0];
                newUser.Password = userInfo[1];
                string[] roles = userInfo[2].Split(new[] { "," }, StringSplitOptions.None);
                newUser.Roles.AddRange(roles);

                _users.Add(newUser);
            }
        }

        public static bool Authenticate(string userName, string userPassword)
        {
            foreach (var user in _users)
            {
                if (user.Name == userName)
                {
                    if (user.Password == userPassword)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return false;
        }

        public static bool UserBelongToRoles(string userName, string userRoles)
        {
            if (string.IsNullOrEmpty(userRoles))
            {
                return true;
            }

            UserEntity user = _users.Find(
                (findUser) =>
                {
                    return findUser.Name == userName;
                });

            if (user == null)
            {
                return false;
            }

            string[] roles = userRoles.Split(new[] { ";" }, StringSplitOptions.None);
            foreach (var role in roles)
            {
                if (!user.Roles.Contains(role))
                {
                    return false;
                }
            }

            return true;
        }
    }
}
